package com.xy.etl.ds.strategy;

import com.xy.etl.ds.SQResult;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class SqlBuilder {
    /**
     * 条件
     */
    protected StringBuilder sqlSegment = new StringBuilder();
    /**
     * 参数
     */
    protected List<Object> paramList = new ArrayList<>();


    /**
     * SQL片段
     *
     * @param segment
     * @param params
     */
    public SqlBuilder append(String segment, Object... params) {
        if (segment != null && segment.length() > 0) {
            sqlSegment.append(segment);
        }
        if (params != null && params.length > 0) {
            List<Object> values = new ArrayList<>(params.length);
            for (Object param : params) {
                values.add(param);
            }
            paramList.addAll(values);
        }
        return this;
    }

    /**
     * SQL片段
     *
     * @param params
     */
    public SqlBuilder param(Object... params) {
        if (params != null && params.length > 0) {
            List<Object> values = new ArrayList<>(params.length);
            for (Object param : params) {
                values.add(param);
            }
            paramList.addAll(values);
        }
        return this;
    }

    /**
     * SQL片段
     * (in /not in )
     *
     * @param column
     * @param params
     * @return
     */
    public SqlBuilder foreach(String column, Collection<? extends Object> params) {
        if (column == null || params == null || params.size() <= 0) {
            return this;
        }
        sqlSegment.append(column).append("( ");
        if (params != null && params.size() > 0) {
            boolean first = true;
            for (Object param : params) {
                if (!first) {
                    sqlSegment.append(",");
                }
                first = false;
                sqlSegment.append("?");
                paramList.add(param);
            }
        }
        sqlSegment.append(") ");
        return this;
    }

    /**
     * 构建
     *
     * @return
     */
    public SQResult build() {
        List<List<Object>> valueList = new ArrayList<>();
        if (paramList != null && paramList.size() > 0) {
            valueList.add(paramList);
        }
        return new SQResult().setSql(sqlSegment.toString()).setValueList(valueList);
    }

}
